package com.zzx.schoolfellow.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @program: schoolfeoolw_backend
 * @description: 后端允许跨域
 * @author: zzx
 * @create: 2023-03-09 09:32
 **/
@Configuration  //Configuration自动注入
public class GlobalWebMvcConfigurer  implements WebMvcConfigurer {
    /**
     * 跨域的mapping
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") //允许域
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")  //允许的方法
                .allowCredentials(true) //允许跨越发送cookie
                .maxAge(3600) //最大时限
                .allowedHeaders("*");  //允许的原始头信息
    }

    //跨域的过滤器
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //允许所有域名进行跨域调用
        config.addAllowedOrigin("*");
        //允许跨越发送cookie
        config.setAllowCredentials(true);
        //放行全部原始头信息
        config.addAllowedHeader("*");
        //允许所有请求方法跨域调用
        config.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
